package com.platform.core.web.controller;

import cn.hutool.core.collection.CollUtil;
import com.platform.comm.util.WebIOUtil;
import com.platform.vo.ExportRecordsDto;
import com.platform.vo.FileImportDetailDto;
import com.platform.vo.ImportRecordsDto;
import com.platform.comm.common.service.ComBatchExportService;
import com.platform.comm.common.service.ComBatchImportService;
import com.platform.comm.common.service.CommQueryExportService;
import com.platform.comm.common.service.CommQueryImportService;
import com.platform.comm.entity.CommDataInfoEntity;
import com.platform.comm.service.ICommDataInfoBiz;
import com.platform.comm.web.results.DataJsonResult;
import com.platform.comm.web.results.JsonResult;
import com.platform.comm.web.results.PageListJsonResult;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Map;

/**
 * Description: 通用批量导入导出
 *
 * @author lx
 * Created on 2020/01/16
 **/
@Controller
@Scope("prototype")
@RequestMapping(name = "通用批量导入导出", path = "/management/comm")
@Log4j2
public class SysCommController extends BaseController {

    private final ICommDataInfoBiz commDataInfoBiz;
    private final ComBatchImportService comBatchImportService;
    private final CommQueryImportService commQueryImportService;
    private final ComBatchExportService comBatchExportService;
    private final CommQueryExportService commQueryExportService;

    public SysCommController(ICommDataInfoBiz commDataInfoBiz, ComBatchImportService comBatchImportService,
                             CommQueryImportService commQueryImportService, ComBatchExportService comBatchExportService,
                             CommQueryExportService commQueryExportService) {
        this.commDataInfoBiz = commDataInfoBiz;
        this.comBatchImportService = comBatchImportService;
        this.commQueryImportService = commQueryImportService;
        this.comBatchExportService = comBatchExportService;
        this.commQueryExportService = commQueryExportService;
    }


    /**
     * 普通批量导入方法
     *
     * @param paramsMap  参数
     * @param uploadFile 文件
     * @return 返回结果信息
     */
    @RequestMapping(path = "/commDataImport", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult startImport(@RequestParam Map<String, String> paramsMap, @RequestParam MultipartFile uploadFile) {
        JsonResult jsonResult = JsonResult.of();
        try {
            paramsMap.put("funName", "sys");
            CommDataInfoEntity commDataImpEntity = this.commDataInfoBiz.saveRecord(paramsMap, uploadFile);
            paramsMap.put("importId", commDataImpEntity.getId());
            comBatchImportService.startImportJob(paramsMap);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            jsonResult = JsonResult.of(ex);
        }

        return jsonResult;
    }

    /**
     * 执行批量导出
     *
     * @param map 参数
     * @return ResponseEntity<String>
     */
    @PostMapping(name = "执行批量导出", path = "/commDataExport")
    @ResponseBody
    public JsonResult startComExportJob(@RequestBody Map<String, String> map) {
        JsonResult jsonResult = JsonResult.success();
        try {
            comBatchExportService.startExportJob(map);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            jsonResult.setMessage(ex.getMessage());
        }
        return jsonResult;
    }

    /**
     * 分页查询通用导入记录列表
     *
     * @param map 请求数据  包含分页信息 及查询条件
     * @return PageListJsonResult<ImportRecordsDto>·
     */
    @PostMapping(name = "查看导入记录", path = "/queryImportRecords")
    @ResponseBody
    public PageListJsonResult<ImportRecordsDto> queryImportRecords(@RequestBody Map<String, String> map) {
        MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
        if (CollUtil.isNotEmpty(map)) {
            map.forEach(parameters::add);
        }
        return PageListJsonResult.of(commQueryImportService.queryImportRecords(getPageable(map), parameters));
    }

    /**
     * 查询通用导入详情
     *
     * @param map 请求数据  包含导入关联的数据id
     * @return DataJsonResult
     */
    @PostMapping(name = "查看导入详情", path = "/queryImportDetails")
    @ResponseBody
    public DataJsonResult<FileImportDetailDto> queryImportDetails(@RequestBody Map<String, String> map) {
        return commQueryImportService.queryImportDetails(map.get("comDataId"));
    }

    /**
     * 查询通用导入中错误数据
     *
     * @param map 请求数据  包含导入关联的数据id
     * @return DataJsonResult
     */
    @PostMapping(name = "查看错误详情", path = "/queryErrorExcelInfo")
    @ResponseBody
    public DataJsonResult<?> queryErrorExcelInfo(@RequestBody Map<String, String> map) {
        return commQueryImportService.queryErrorExcelInfo(map.get("comDataId"));
    }

    /**
     * 分页查询通用导出记录列表
     *
     * @param map 请求数据  包含分页信息 及查询条件
     * @return PageListJsonResult<ExportRecordsDto>
     */
    @PostMapping(name = "查看导出记录", path = "/queryExportRecords")
    @ResponseBody
    public PageListJsonResult<ExportRecordsDto> queryExportRecords(@RequestBody Map<String, String> map) {
        MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
        if (CollUtil.isNotEmpty(map)) {
            map.forEach(parameters::add);
        }
        return commQueryExportService.queryExportRecords(getPageable(map), parameters);
    }

    /**
     * 通用导出文件下载
     *
     * @param map      请求参数体
     * @param response 响应对象
     */
    @PostMapping(name = "通用下载导出文件", path = "/downloadExport")
    public void downloadExport(@RequestBody Map<String, String> map, HttpServletResponse response) {
        Pair<Path, String> info = commQueryExportService.getCommFile(map.get("id"));
        try {
            WebIOUtil.download(info.getLeft(), response, info.getRight());
        } catch (IOException e) {
            throw new RuntimeException("下载导出文件异常", e);
        }
    }

}
